import { reactive } from 'vue'

// 模拟用户数据存储
const users = [
  { id: 1, username: 'testuser', email: 'test@example.com', password: 'password123', isMember: false, isAdmin: false },
  { id: 2, username: 'memberuser', email: 'member@example.com', password: 'password123', isMember: true, isAdmin: false },
  { id: 3, username: 'gaozimo', email: 'admin@example.com', password: 'gaozimo0712', isMember: true, isAdmin: true }
]

// 用户状态
const state = reactive({
  currentUser: null,
  isAuthenticated: false
})

// 用户操作
export const userStore = {
  // 获取当前用户状态
  getState() {
    return state
  },
  
  // 用户登录
  login(identifier, password) {
    // 查找用户（可以是用户名或邮箱）
    const user = users.find(u => 
      u.username === identifier || u.email === identifier
    )
    
    // 验证密码
    if (user && user.password === password) {
      // 设置当前用户
      state.currentUser = {
        id: user.id,
        username: user.username,
        email: user.email,
        isMember: user.isMember || false,
        isAdmin: user.isAdmin || false
      }
      state.isAuthenticated = true
      return { success: true, user: state.currentUser }
    }
    
    return { success: false, message: '用户名或密码错误' }
  },
  
  // 用户注册
  register(username, email, password, isMember = false) {
    // 检查用户名是否已存在
    if (users.some(u => u.username === username)) {
      return { success: false, message: '用户名已存在' }
    }
    
    // 检查邮箱是否已存在
    if (users.some(u => u.email === email)) {
      return { success: false, message: '邮箱已被注册' }
    }
    
    // 创建新用户
    const newUser = {
      id: users.length + 1,
      username,
      email,
      password, // 注意：实际项目中密码需要加密存储
      isMember
    }
    
    users.push(newUser)
    
    // 自动登录
    state.currentUser = {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      isMember: newUser.isMember,
      isAdmin: newUser.isAdmin || false
    }
    state.isAuthenticated = true
    
    return { success: true, user: state.currentUser }
  },
  
  // 用户登出
  logout() {
    state.currentUser = null
    state.isAuthenticated = false
    return { success: true }
  },
  
  // 升级为会员
  upgradeToMember() {
    if (state.isAuthenticated && state.currentUser) {
      // 更新当前用户状态
      state.currentUser.isMember = true
      
      // 更新用户数组中的用户信息
      const userIndex = users.findIndex(u => u.id === state.currentUser.id)
      if (userIndex !== -1) {
        users[userIndex].isMember = true
      }
      
      return { success: true, message: '成功升级为会员！' }
    }
    
    return { success: false, message: '请先登录' }
  },
  
  // 检查是否为会员
  isMember() {
    return state.isAuthenticated && state.currentUser && state.currentUser.isMember
  }
}